import { ref, onUnmounted } from "vue";
import { SSE } from "sse.js";

export function useSSE(
  url,
  {
    headers = {},
    payload = null,
    method = "GET",
    autoReconnect = true,
    reconnectDelay = 3000, // 重连间隔
    maxRetries = Infinity, // 最大重试次数
    useLastEventId = true,
  } = {}
) {
  const data = ref(null); // 最新消息
  const error = ref(null); // 错误信息
  const isConnected = ref(false); // 连接状态
  const eventMap = new Map(); // 事件监听表

  let es = null;
  let retryCount = 0;

  const connect = () => {
    es = new SSE(url, {
      headers,
      payload,
      method,
      withCredentials: false,
      autoReconnect,
      reconnectDelay,
      maxRetries,
      useLastEventId,
    });

    es.addEventListener("open", () => {
      isConnected.value = true;
      retryCount = 0;
    });

    es.addEventListener("message", (e) => {
      let payload = e.data;
      try {
        payload = JSON.parse(e.data);
      } catch {}
      data.value = payload;
      trigger("message", payload);
    });

    es.addEventListener("error", (e) => {
      error.value = e;
      isConnected.value = false;
      trigger("error", e);
    });

    // 自定义事件绑定
    eventMap.forEach((handlers, eventName) => {
      es.addEventListener(eventName, (e) => {
        let payload = e.data;
        try {
          payload = JSON.parse(e.data);
        } catch {}
        handlers.forEach((fn) => fn(payload));
      });
    });

    es.stream();
  };

  const on = (eventName, handler) => {
    if (!eventMap.has(eventName)) {
      eventMap.set(eventName, []);
    }
    eventMap.get(eventName).push(handler);
  };

  const trigger = (eventName, payload) => {
    if (eventMap.has(eventName)) {
      eventMap.get(eventName).forEach((fn) => fn(payload));
    }
  };

  const close = () => {
    if (es) es.close();
    isConnected.value = false;
  };

  connect();
  onUnmounted(close);

  return { data, error, isConnected, on, close };
}
